#ifndef WEBSOCKET_SESSION_H
#define WEBSOCKET_SESSION_H

#include <memory>
#include <string>
#include <thread>
#include <atomic>
#include <vector>
#include <functional>
#include "common/websocket_frame.h"

namespace websocket {

class WebSocketSession : public std::enable_shared_from_this<WebSocketSession> {
public:
    WebSocketSession(int socket);
    ~WebSocketSession();
    
    // 启动会话处理
    void start();
    
    // 发送消息
    void sendText(const std::string& message);
    void sendBinary(const std::vector<uint8_t>& data);
    void sendPing();
    void close(uint16_t code = 1000, const std::string& reason = "");
    
    // 获取会话信息
    int getSocket() const { return socket_; }
    bool isConnected() const { return connected_; }
    std::string getRemoteAddress() const { return remote_address_; }
    
    // 设置回调函数
    using MessageCallback = std::function<void(const std::string&)>;
    using CloseCallback = std::function<void()>;
    
    void setMessageCallback(MessageCallback callback) { message_callback_ = callback; }
    void setCloseCallback(CloseCallback callback) { close_callback_ = callback; }

private:
    void readLoop();
    bool readData(std::vector<uint8_t>& buffer, size_t size);
    bool sendData(const std::vector<uint8_t>& data);
    void handleWebSocketFrame(const WebSocketFrame& frame);
    void cleanup();

    int socket_;
    std::atomic<bool> connected_;
    std::atomic<bool> closing_;
    std::thread read_thread_;
    std::string remote_address_;
    
    MessageCallback message_callback_;
    CloseCallback close_callback_;
};

} // namespace websocket

#endif // WEBSOCKET_SESSION_H